package conceptmaniax.hotelapp.activities;

 import java.text.ParseException;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;

import conceptmaniax.hotelapp.config.Constants;
import conceptmaniax.hotelapp.managers.RequestManager;
import conceptmaniax.hotelapp.util.GeneralUtils;
import conceptmaniax.hotelapp.util.database.DataHelper;
import conceptmaniax.hotelapp.util.geo.GeoUtils;

public class DetailMapActivity extends FragmentActivity implements LocationListener {
	
	private GoogleMap map;
	private DataHelper dataHelper = new DataHelper(this, Constants.DATABASE_NAME);
	private LocationManager locationManager;
	private String gpsProvider;
	private Location location;
    private Button showInfo;
    private Button showServices;
    private Button showGuide;
    private Button showBooking;
    private TableLayout callout;
    private ListView callout_list;
    private TableLayout homeScreen;
    private Button requests;
	protected TextView counter;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sub1_map_menu);
		
		// location related actions
		this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		this.gpsProvider = this.locationManager.getBestProvider(GeoUtils.getCriteria(), true);										
		if ( this.gpsProvider != null ) {
			this.location = this.locationManager.getLastKnownLocation(gpsProvider);
			this.locationManager.requestLocationUpdates(this.gpsProvider, Constants.MINIMUM_TIME_BETWEEN_UPDATES, Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
		}
		
		//Go back to HomePage Button
		final Button go_to_home = (Button) findViewById(R.id.homeButton);
		go_to_home.setOnClickListener(new View.OnClickListener() {
			public void onClick(final View view) {
				final Intent homePageIntent = new Intent(Constants.HOMEPAGE_ACTIVITY);
		    	startActivity(homePageIntent);
			}
		});
		
     	final Button routeMapButton = (Button) findViewById(R.id.driveme_button);
     	routeMapButton.setOnClickListener(new OnClickListener() {
     			
        	@Override
        	public void onClick(final View view) {
        		routeMap();
        	}
        });
     	
		showInfo = (Button) findViewById(R.id.hotel_button);
		showServices = (Button) findViewById(R.id.services_button);
		showGuide = (Button) findViewById(R.id.guide_button);
		showBooking = (Button) findViewById(R.id.booking_button);
		homeScreen = (TableLayout) findViewById(R.id.sub1map_tablelayout1);
 		requests = (Button) findViewById(R.id.requestsButton);
		callout = (TableLayout)findViewById(R.id.callout_table);
		callout_list = (ListView)findViewById(R.id.callout_listview);
		counter = (TextView) findViewById(R.id.counter);

		// Set Map based on Location
		this.map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.simple_map_mapview)).getMap();
		if (this.map != null) {
			final String latidute;
			final String longitude;
			this.map.clear();
			final String itemName = "Villa Paradise";
			latidute = Constants.DEFAULT_LATITUDE;
			longitude = Constants.DEFAULT_LONGITUDE;
			addPointToMap(GeoUtils.getLatLng(latidute, longitude), itemName, false);
			this.map.setTrafficEnabled(true);
			this.map.setMyLocationEnabled(true);
			this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(GeoUtils.getLatLng(latidute, longitude), 10));
		}
	}
	
	private void routeMap() {
		final Intent routeMapIntent = new Intent(Constants.ROUTE_MAPVIEW_ACTIVITY);
		final String[] location = new String[4];
		
		if ( this.location != null ) {
			location[0] = Double.toString( this.location.getLatitude() );
			location[1] = Double.toString( this.location.getLongitude() );
		}
		location[2] = Constants.DEFAULT_LATITUDE;
		location[3] = Constants.DEFAULT_LONGITUDE;
		routeMapIntent.putExtra("LOCATION", location);
		startActivity(routeMapIntent);
	}
	
	private void addPointToMap(final LatLng latLng, final String name, boolean self) {
	    final MarkerOptions markerOptions = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.fromResource(getMapIcon(self)));
	    if (name != null) markerOptions.title(name);
	    this.map.addMarker(markerOptions);
	}
	
	private int getMapIcon(boolean self) {
		int mapIconId;
		mapIconId = getResources().getIdentifier(Constants.GENERIC_MAP_PIN, "drawable", Constants.ACTIVITY_PREF);
		return mapIconId;
	}
	
	@SuppressWarnings("unused")
	private void pointToLocation(final GeoPoint geoPoint) {

	}
	
	@Override
	protected void onPause() {
		super.onPause();
		this.locationManager.removeUpdates(this);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if ( this.dataHelper != null ) this.dataHelper.close();
		unbindDrawables(findViewById(R.id.sub1map_relative));
	    System.gc();
	}
	
	private void unbindDrawables(final View view) {
        if (view.getBackground() != null) {
        	view.getBackground().setCallback(null);
        }
        
        if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            	unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            ((ViewGroup) view).removeAllViews();
        }
    }
	
	@Override
	protected void onResume() {
		super.onResume();
		RequestManager.getInstance().init(this);

		// TO-DO: tell user if she wants to turn on GPS
		if (this.gpsProvider != null) {
			this.locationManager.requestLocationUpdates(this.gpsProvider, Constants.MINIMUM_TIME_BETWEEN_UPDATES, Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this);
		}
		SetButtonActivity.getInstance().setRecognition(false);
		SetButtonActivity.getInstance().setButtons(this, showInfo, showServices, showGuide, showBooking, callout, callout_list, homeScreen, requests);

		try {
			int counter = RequestManager.getInstance().getRequestCount();
			this.counter.setText(""+counter);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    // manage message counter
	    if (this.counter.getText().equals("0")) 
	        this.counter.setVisibility(View.INVISIBLE);
	     else
	        this.counter.setVisibility(View.VISIBLE);
	}

	@Override
	public void onLocationChanged(final Location loc) {
		this.location = loc;
	}

	@Override
	public void onProviderDisabled(final String provider) { }
	
	@Override
	public void onProviderEnabled(final String provider) { }
	
	@Override
	public void onStatusChanged(final String provider, final int status, final Bundle extras) { }
	
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {		
		return super.onCreateOptionsMenu(GeneralUtils.createOptionsMenu(this, menu));
	}
	
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		GeneralUtils.onOptionsItemSelected(this, item);
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	protected Dialog onCreateDialog(final int id) {
		return GeneralUtils.createAboutUsDialog(this);
	}
}
